package com.web.webstart.base.util.shortmsg.emay.channel.httpclient;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

import javax.servlet.http.HttpServletRequest;

public class HttpClientUtil {
    private static Logger logger = Logger.getLogger(HttpClientUtil.class);
    private static HttpClient httpClient = null;

    // 构造单例
    private HttpClientUtil() {

        MultiThreadedHttpConnectionManager httpConnectionManager = new MultiThreadedHttpConnectionManager();
        HttpConnectionManagerParams params = new HttpConnectionManagerParams();
        // 默认连接超时时间
        params.setConnectionTimeout(5000);
        // 默认读取超时时间
        params.setSoTimeout(10000);
        // 默认单个host最大连接数
        params.setDefaultMaxConnectionsPerHost(100);// very important!!
        // 最大总连接数
        params.setMaxTotalConnections(256);// very important!!
        httpConnectionManager.setParams(params);

        httpClient = new HttpClient(httpConnectionManager);

        httpClient.getParams().setConnectionManagerTimeout(3000);
        // httpClient.getParams().setIntParameter("http.socket.timeout", 10000);
        // httpClient.getParams().setIntParameter("http.connection.timeout", 5000);
    }

    private static class ClientUtilInstance {
        private static final HttpClientUtil ClientUtil = new HttpClientUtil();
    }

    public static HttpClientUtil getInstance() {
        return ClientUtilInstance.ClientUtil;
    }

    /**
     * 发送http GET请求，并返回http响应字符串
     *
     * @param urlstr 完整的请求url字符串
     * @return
     */
    public String doGetRequest(String urlstr) {
        String response = "";

        HttpMethod httpmethod = new GetMethod(urlstr);
        try {
            int statusCode = httpClient.executeMethod(httpmethod);
            InputStream _InputStream = null;
            if (statusCode == HttpStatus.SC_OK) {
                _InputStream = httpmethod.getResponseBodyAsStream();
            }
            if (_InputStream != null) {
                response = GetResponseString(_InputStream, "UTF-8");
            }
        } catch (HttpException e) {
            logger.error("获取响应错误，原因：" + e.getMessage());
            e.printStackTrace();
        } catch (IOException e) {
            logger.error("获取响应错误，原因1：" + e.getMessage());
            e.printStackTrace();
        } finally {
            httpmethod.releaseConnection();

        }
        return response;
    }

    /**
     * 发送http Post请求，并返回http响应字符串
     *
     * @param urlstr 完整的请求url字符串
     * @return
     */
    public String doPostRequest(String urlstr, Map<String, String> paramsMap) {

        //POST的URL
        HttpPost httppost = new HttpPost(urlstr);
        //建立HttpPost对象
        List<org.apache.http.NameValuePair> params = new ArrayList<>();
        //建立一个NameValuePair数组，用于存储欲传送的参数
        if (paramsMap != null) {
            for (Map.Entry entry : paramsMap.entrySet()) {
                String key = entry.getKey().toString();
                String val = entry.getValue().toString();
                params.add(new BasicNameValuePair(key , val ));
            }
        }
        String result = "";
        try {
            //添加参数
            httppost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
            //设置编码
            HttpResponse response = new DefaultHttpClient().execute(httppost);
            //发送Post,并返回一个HttpResponse对象
            if (response.getStatusLine().getStatusCode() == 200) {//如果状态码为200,就是正常返回
                InputStream _InputStream = response.getEntity().getContent();
                if (_InputStream != null) {
                    result = GetResponseString(_InputStream, "UTF-8");
                }
            }
        } catch (Exception e) {
            logger.error("获取响应错误，原因：" + e.getMessage());
        }

        return result;
    }

    /**
     * post请求
     * @param url
     * @param param
     * @return
     * @throws IOException
     */
    public static String doPostRequest2(String url, Map<String,String> params){
        CloseableHttpClient httpclientTemp = HttpClientUtil.createDefault();
        HttpPost httpPost = new HttpPost(url);
        //拼接参数
        List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>();
        for (Map.Entry<String, String> entry : params.entrySet()) {
            String key = entry.getKey().toString();
            String value = entry.getValue().toString();
            System.out.println("key=" + key + " value=" + value);
            BasicNameValuePair pair = new BasicNameValuePair(key, value);
            list.add(pair);
        }
        CloseableHttpResponse response=null;
        try {
            httpPost.setEntity(new UrlEncodedFormEntity(list));
            response = httpclientTemp.execute(httpPost);
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        /**请求发送成功，并得到响应**/
        String result="";
        if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
            HttpEntity httpEntity = response.getEntity();
            try {
                result = EntityUtils.toString(httpEntity);
            } catch (ParseException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return result;
    }


    private static HttpPost postForm(String url, Map<String, String> params) {

        HttpPost httpost = new HttpPost(url);
        List nameValuePairs = new ArrayList<>();

        Set<String> keySet = params.keySet();
        for (String key : keySet) {
            nameValuePairs.add(new NameValuePair(key, params.get(key)));
        }

        try {
            logger.info("set utf-8 form entity to httppost");
            httpost.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return httpost;
    }

    /**
     * @param _InputStream
     * @param Charset
     * @return
     */
    private String GetResponseString(InputStream _InputStream, String Charset) {
        String response = "";
        try {
            if (_InputStream != null) {
                StringBuffer buffer = new StringBuffer();
                InputStreamReader isr = new InputStreamReader(_InputStream, Charset);
                Reader in = new BufferedReader(isr);
                int ch;
                while ((ch = in.read()) > -1) {
                    buffer.append((char) ch);
                }
                response = buffer.toString();
                buffer = null;
            }
        } catch (Exception e) {
            logger.error("获取响应错误，原因：" + e.getMessage());
            response = response + e.getMessage();
            e.printStackTrace();
        }
        return response;
    }

    public static String getHttpFullURL(String requestStr, String paramString) {
        if (requestStr != null) {
            // Only add the query string if it isn't empty and it
            // isn't equal to '?'.
            if (!paramString.equals("") && !paramString.equals("?")) {
                requestStr += requestStr.toString().contains("?") ? "&" : "?";
                requestStr += paramString;
            }
        }
        return requestStr;
    }


    public static String getHttpFullURL(HttpServletRequest request) {
        String url = request.getRequestURL().toString();
        String paramString = request.getQueryString();
        if (url != null) {
            // Only add the query string if it isn't empty and it
            // isn't equal to '?'.
            if (!paramString.equals("") && !paramString.equals("?")) {
                url += url.toString().contains("?") ? "&" : "?";
                url += paramString;
            }
        }
        return url;
    }

    /**
     * Creates {@link CloseableHttpClient} instance with default
     * configuration.
     */
    public static CloseableHttpClient createDefault() {
        return HttpClientBuilder.create().build();
    }


    public static void main(String[] args) {
        //String url = "http://esms.etonenet.com/sms/mt?spid=3060&sppassword=hbkj3060&das=8618611178949&command=MULTI_MT_REQUEST&sm=a1beccd4b1a6a1bf20cda8b5c0bdd3c8ebcdeab3c9a3a1&dc=15";
        // System.out.println(doGetRequest(url));
    }
}
